<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="/command/jquery/jquery-3.4.1.js"></script>
    <style type="text/css">
        .talk_con {
            width: 600px;
            height: 500px;
            border: 1px solid #666;
            margin: 0px auto 0;
            background: #f9f9f9;
        }

        .talk_show {
            width: 580px;
            height: 420px;
            border: 1px solid #666;
            background: #fff;
            margin: 10px auto 0;
            overflow: auto;
        }

        .talk_input {
            width: 580px;
            margin: 10px auto 0;
        }

        .whotalk {
            width: 80px;
            height: 30px;
            float: left;
            outline: none;
        }

        .talk_word {
            width: 420px;
            height: 26px;
            padding: 0px;
            float: left;
            margin-left: 10px;
            outline: none;
            text-indent: 10px;
        }

        .talk_sub {
            width: 56px;
            height: 30px;
            float: left;
            margin-left: 10px;
        }

        .atalk {
            float: left;
            margin: 10px;
            height: 40px;
            width: 400px;
        }

        .atalk span {
            display: inline-block;
            background: #0181cc;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
        }

        .btalk {
            float: right;
            margin: 10px;
            height: 40px;
            width: 400px;
            text-align: right;
        }

        .btalk span {
            display: inline-block;
            background: #ef8201;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
        }

        .center {
            float: right;
            margin: 10px;
            height: 40px;
            width: 400px;
            text-align: center;
        }

        .center span {
            display: inline-block;
            border-radius: 10px;
            color: black;
            padding: 5px 10px;
        }


        .cen {
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        //以下获得目标用户头像
        window.onload = function () {
            $.ajax({
                type: "POST",
                url: "/getuserinfobyid/" + oid,
                async: false,
                success: function (result) {
                    if (result != null) {
                        let oPic = result.pic;
                        let oName = result.username;
                        document.getElementById("oName").innerHTML += '<div class="cen">' + oName + '</div>';
                        sessionStorage.setItem("oPic", oPic);
                    }
                },
                error: function (errorMsg) {
                    alert("获取头像失败");
                }
            });
        };
    </script>
</head>
<body>
<div class="talk_con">
    <div id="oName"></div>
    <div class="talk_show" id="words">
        <!--        <div class="atalk"><span id="asay">A说：吃饭了吗？</span></div>-->
        <!--        <div class="btalk"><span id="bsay">B说：还没呢，你呢？</span></div>-->
    </div>
    <div class="talk_input">
        <!--        <select class="whotalk" id="who">-->
        <!--            <option value="0">A说：</option>-->
        <!--            <option value="1">B说：</option>-->
        <!--        </select>-->
        <input type="button" value="清屏" class="talk_sub" id="clearMessage">
        <input type="button" value="历史" class="talk_sub" id="history">
        <div>
            <input type="text" class="talk_word" id="talkwords">
            <input type="button" value="发送" class="talk_sub" id="talksub">
        </div>
    </div>
</div>

<script>

    let href = window.location.href;
    let arr = href.split('/');
    let idData = arr[arr.length - 1];
    let idArr = idData.split("&");
    let uid = idArr[0];
    let oid = idArr[1];
    let username = sessionStorage.getItem("username");
    let Words = document.getElementById("words");

    let TalkWords = document.getElementById("talkwords");
    let TalkSub = document.getElementById("talksub");
    let clearMessage = document.getElementById("clearMessage");

    TalkSub.onclick = function () {
        if (TalkWords.value == "") {
            // 消息为空时弹窗
            alert("消息不能为空");
            return;
        } else {
            sendMessage(TalkWords.value);
            setMyMessage();
            TalkWords.value = "";
        }
    };

    document.getElementById("history").onclick = function () {
        openWin('/chatHistoryView/' + uid + '&' + oid, 620, 580);
    };

    function openWin(name, iWidth, iHeight) {
        //获得窗口的垂直位置
        var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
        //获得窗口的水平位置
        var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
        window.open(name, "history", 'height=' + iHeight + ',innerHeight=' + iHeight +
            ', width = ' + iWidth + ', innerWidth = ' + iWidth + ', top = ' + iTop + ', left = ' + iLeft +
            ', status = no, toolbar = no, menubar = no, location = no, resizable = yes, scrollbars = 0, titlebar = no');
    }


    clearMessage.onclick = function () {
        $("#words").empty();
        $("#talkwords").focus();
    };

    let webSocket = null;
    if ("WebSocket" in window) {
        webSocket = new WebSocket("ws://localhost:8080/chat/" +
            sessionStorage.getItem("uid") +
            "&" + oid
        );
    } else {
        alert("浏览器不支持webSocket！");
    }

    webSocket.onopen = function () {
        console.log("连接成功");
    };
    //刷新div

    webSocket.onmessage = function (event) {
        let obj = JSON.parse(event.data);

        //console.log(obj);

        let type = obj.type;
        let message = obj.message;
        if (type[0].type === "message") {
            setMessage(message[0].fromName, message[0].messageText)
        } else if (type[0].type === "Unread" && message.length !== 0) {
            message.forEach(setUnread);
            let time = message[message.length - 1].messageDate;
            Words.innerHTML += '<div class="btalk"><span>以上未读</span></div>';
            Words.innerHTML += '<div class="center"><span>' + time + '</span></div>';
        }
    };

    function setUnread(item) {
        setMessage(item.fromName, item.messageText)
    }

    // 显示用户头像
    let pic = sessionStorage.getItem("pic");
    let img = document.createElement("img");
    img.src = "data:image/jpeg;base64," + pic;
    img.width = 30;
    img.height = 30;

    function setMyMessage() {
        let str = '<div class="atalk"><div id = "image" style="float: left"></div> <div style="float: left"><span>' + TalkWords.value + '</span></div></div>';
        Words.innerHTML = Words.innerHTML + str;

        $("[id=image]").html(img);
    }



    function setMessage(fromName, messageText) {
        let str = '<div class="btalk"><div id = "oImage" style="float: right"></div><div style="float: right"><span>' + messageText + '</span></div></div>';
        Words.innerHTML = Words.innerHTML + str;
        //目标用户头像
        let oPic = sessionStorage.getItem("oPic");
        let oImg = document.createElement("img");
        oImg.src = "data:image/jpeg;base64," + oPic;
        oImg.width = 30;
        oImg.height = 30;
        $("[id=oImage]").html(oImg);
    }

    function sendMessage(TalkWords) {
        let message = JSON.stringify({
            'messageText': TalkWords,
            'toId': oid,
            'fromName': username,
            'fromId': uid
        });

        webSocket.send(message);
    }


    //关闭按钮调用函数
    function clo() {
        webSocket.close(3000, "强制关闭");
    }


    window.onbeforeunload = function () {
        clo();
    };


</script>
</body>
</html>
